package cn.stylefeng.guns.sys.modular.system.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.base.pojo.node.MenuNode;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.shiro.ShiroUser;
import cn.stylefeng.guns.sys.core.constant.Const;
import cn.stylefeng.guns.sys.core.constant.factory.ConstantFactory;
import cn.stylefeng.guns.sys.core.constant.state.ManagerStatus;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.shiro.service.UserAuthService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.factory.UserFactory;
import cn.stylefeng.guns.sys.modular.system.mapper.UserMapper;
import cn.stylefeng.guns.sys.modular.system.model.UserDto;
import cn.stylefeng.roses.core.datascope.DataScope;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2018-12-07
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserAuthService userAuthService;

    /**
     * 添加用戶
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:51
     */
    public void addUser(UserDto user) {

        // 判断账号是否重复
        User theUser = this.getByAccount(user.getAccount());
        User theUsers = this.getByAccounts(user.getAccount());
        if (theUser != null || theUsers != null) {
            throw new ServiceException(BizExceptionEnum.USER_ALREADY_REG);
        }

        // 完善账号信息
        String salt = ShiroKit.getRandomSalt(5);
        String password = ShiroKit.md5(user.getPassword(), salt);

        this.save(UserFactory.createUser(user, password, salt));
    }

    private User getByAccounts(String account) {
        return this.baseMapper.getByAccounts(account, null);
    }

    /**
     * 修改用户
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:53
     */
    public void editUser(UserDto user) {
        User oldUser = this.getById(user.getUserId());

        if (ShiroKit.hasRole(Const.ADMIN_NAME)) {
            this.updateById(UserFactory.editUser(user, oldUser));
        } else {
            this.assertAuth(user.getUserId());
            ShiroUser shiroUser = ShiroKit.getUserNotNull();
            if (shiroUser.getId().equals(user.getUserId())) {
                this.updateById(UserFactory.editUser(user, oldUser));
            } else {
                throw new ServiceException(BizExceptionEnum.NO_PERMITION);
            }
        }
    }

    /**
     * 删除用户
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:54
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long userId) {

        //不能删除超级管理员
        if (userId.equals(Const.ADMIN_ID)) {
            throw new ServiceException(BizExceptionEnum.CANT_DELETE_ADMIN);
        }
        this.assertAuth(userId);
        this.setStatus(userId, ManagerStatus.DELETED.getCode());

        //删除对应的oauth2绑定表
        SqlRunner.db().delete("delete from oauth_user_info where user_id = {0}", userId);
    }

    /**
     * 修改用户状态
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:45
     */
    public int setStatus(Long userId, String status) {
        return this.baseMapper.setStatus(userId, status);
    }

    /**
     * 修改密码
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:45
     */
    public void changePwd(String oldPassword, String newPassword) {
        Long userId = ShiroKit.getUserNotNull().getId();
        User user = this.getById(userId);

        String oldMd5 = ShiroKit.md5(oldPassword, user.getSalt());

        if (user.getPassword().equals(oldMd5)) {
            String newMd5 = ShiroKit.md5(newPassword, user.getSalt());
            user.setPassword(newMd5);
            this.updateById(user);
        } else {
            throw new ServiceException(BizExceptionEnum.OLD_PWD_NOT_RIGHT);
        }
    }

    /**
     * 根据条件查询用户列表
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:45
     */
    public Page<Map<String, Object>> selectUsers(DataScope dataScope, String name, String beginTime, String endTime, Long deptId) {
        Page page = LayuiPageFactory.defaultPage();
        return this.baseMapper.selectUsers(page, dataScope, name, beginTime, endTime, deptId);
    }

    /**
     * 设置用户的角色
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:45
     */
    public int setRoles(Long userId, String roleIds) {
        return this.baseMapper.setRoles(userId, roleIds);
    }

    /**
     * 通过账号获取用户
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:46
     */
    public User getByAccount(String account) {
        return this.baseMapper.getByAccount(account, null);
    }

    /**
     * 获取用户菜单列表
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:46
     */
    public List<MenuNode> getUserMenuNodes(List<Long> roleList) {
        if (roleList == null || roleList.size() == 0) {
            return new ArrayList<>();
        } else {
            List<MenuNode> menus = menuService.getMenusByRoleIds(roleList);
            return MenuNode.buildTitle(menus);
        }

    }

    /**
     * 判断当前登录的用户是否有操作这个用户的权限
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    public void assertAuth(Long userId) {
        if (ShiroKit.isAdmin()) {
            return;
        }
        List<Long> deptDataScope = ShiroKit.getDeptDataScope();
        User user = this.getById(userId);
        Long deptId = user.getDeptId();
        if (deptDataScope.contains(deptId)) {
            return;
        } else {
            throw new ServiceException(BizExceptionEnum.NO_PERMITION);
        }

    }

    /**
     * 刷新当前登录用户的信息
     *
     * @author fengshuonan
     * @Date 2019/1/19 5:59 PM
     */
    public void refreshCurrentUser() {
        ShiroUser user = ShiroKit.getUserNotNull();
        Long id = user.getId();
        User currentUser = this.getById(id);
        ShiroUser shiroUser = userAuthService.shiroUser(currentUser);
        ShiroUser lastUser = ShiroKit.getUser();
        BeanUtil.copyProperties(shiroUser, lastUser);
    }

    /**
     * 获取用户的基本信息
     *
     * @author fengshuonan
     * @Date 2019-05-04 17:12
     */
    public Map<String, Object> getUserInfo(Long userId) {
        User user = this.getById(userId);
        Map<String, Object> map = UserFactory.removeUnSafeFields(user);

        HashMap<Object, Object> hashMap = CollectionUtil.newHashMap();
        hashMap.putAll(map);
        hashMap.put("roleName", ConstantFactory.me().getRoleName(user.getRoleId()));
        hashMap.put("deptName", ConstantFactory.me().getDeptName(user.getDeptId()));

        return map;
    }

    /*---------------------------activity角色控制------------------------------------------*/

    /**
     * 服务专员
     * 服务专员id：1157187919098679298
     *
     * @return
     */
    public List<String> findServiceAdministrator() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157187919098679298").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 财务专员
     * 财务专员id：1157189371426770945
     *
     * @return
     */
    public List<String> findFinanceCommissioner() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157189371426770945").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 销售服务部经理
     * 销售服务部经理id：1157187294277406721
     *
     * @return
     */
    public List<String> findSalesServiceManager() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157187294277406721").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 售后服务部经理
     * 售后服务部经理id：1157191496860962817
     *
     * @return
     */
    public List<String> findAfterSalesServiceManager() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157191496860962817").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 特许经销商
     * 特许经销商id：1157182559067574273
     *
     * @return
     */
    public List<String> findFranchisedDistributor() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157182559067574273").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 物流发货员
     * 物流发货员id：1157188923353468929
     *
     * @return
     */
    public List<String> findLogisticsShipper() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157188923353468929").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 物流主管
     * 物流主管id：1157187480508698626
     *
     * @return
     */
    public List<String> findLogisticsSupervisor() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157187480508698626").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 物流专员
     * 物流专员id：1157188780055072770
     *
     * @return
     */
    public List<String> findLogisticsCommissioner() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157188780055072770").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 服务主管
     * 服务主管id：1157187377022636033
     *
     * @return
     */
    public List<String> findServiceSupervisor() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157187377022636033").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 售后主管
     * 售后主管id：1157191600355414017
     *
     * @return
     */
    public List<String> findAfterSalesSupervisor() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157191600355414017").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 售后专员
     * 售后专员id：1157193261211717634
     *
     * @return
     */
    public List<String> findAftersalesCommissioner() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157193261211717634").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 销售服务部副经理
     * 销售服务部副经理id：1157187608204283906
     *
     * @return
     */
    public List<String> findSalesDeputyManager() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157187608204283906").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 销售服务部信息主管
     * 销售服务部信息主管id：1157187753973125121
     *
     * @return
     */
    public List<String> findSalesInformationSupervisor() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157187753973125121").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 拓展部区域经理
     */
    public List<String> findQuYu() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157571556226895873").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 拓展部大区经理
     */
    public List<String> findDaQu() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157571418695667714").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }

    /**
     * 拓展部总监
     */
    public List<String> findZongJian() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157571752025395202").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }


    /**
     * 代充值
     */
    public List<String> findSale() {
        //User user = super.getById(userId);
        return this.baseMapper.listByDeptIdAndRoleId("1157187753973125121").stream().map(u -> u.getUserId().toString()).collect(Collectors.toList());
    }


}
